今天來說說View使用強型別與動態型別的差異
在View的開頭處明確指定Model的型別
@model IEnumerable<model物件>
強型別支援IntelliSense,還有較好的效能
強型別傳資料給 View 的方式,是在 return 的時候把物件回傳,return View(object)
@model FirstProject.Models.ModelsName
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.id)
<div class="form-group">
@Html.LabelFor(model => model.姓名, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.姓名, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.姓名, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.內容, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.內容, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.內容, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
由Scaffold產生的View就是一個強型別的資料
未使用@model指示詞宣告型別
不支援IntelliSense和編譯時期檢查,效能也較差
※IntelliSense可以自動完成程式碼片段